﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace ZhaGanSharp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static String strVer, strRver;
        System.Windows.Forms.NotifyIcon nIcon;
        Windows.TopmostTooltip tt;
        public MainWindow()
        {
            InitializeComponent();
            strVer = App.ResourceAssembly.GetName(false).Version.Major + "." + App.ResourceAssembly.GetName(false).Version.Minor + "." + App.ResourceAssembly.GetName(false).Version.Build;
            strRver = App.ResourceAssembly.GetName(false).Version.Revision.ToString();
            this.TextBlock_AppName.DataContext = Properties.Resources.AppName + "  " + strVer;
            this.Title = Properties.Resources.AppName + "  " + strVer;
            this.TextBlock_GetedTimes.Text = "已榨干次数: " + Properties.Settings.Default.GetedTimes.ToString();
            ComboBox_CloudDrive_Init();
            GetRemoteVer();
            this.TextBox_InputURL.Focus();
        }

        #region 检测当前远程版本
        System.Threading.Thread Thread_GetRemoteVer;
        Byte[] byteJson_Ver;String strJson_Ver;
        private void GetRemoteVer(){
            Thread_GetRemoteVer=new System.Threading.Thread(GetRemoteVer_DoWork);
            Thread_GetRemoteVer.Name="ChildThread_GetRemoteVer";
            Thread_GetRemoteVer.IsBackground=true;
            Thread_GetRemoteVer.Start();
        }
        private void GetRemoteVer_DoWork()
        {
            byteJson_Ver = Functions.HttpRequestUtil.Get("http://api.ragnaroks.org/api/zhagansharp/version.php");
            strJson_Ver = System.Text.Encoding.UTF8.GetString(byteJson_Ver, 0, byteJson_Ver.Length);
            if (Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") != "unknown" && Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") != null)
            {
                if (Int32.Parse(strRver) < Int32.Parse(Functions.Main.DecodeJson_Ver(strJson_Ver, "rver")))
                {
                    this.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate
                        {
                            this.TextBlock_RemoteVer.Text += "当前有更新版本: " + Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") + "." + Functions.Main.DecodeJson_Ver(strJson_Ver, "rver");
                            this.TextBlock_RemoteVer_Tooltip.Content = "点此下载新版本: " + Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") + "." + Functions.Main.DecodeJson_Ver(strJson_Ver, "rver");
                            UpdateDownloadURI = "http://static.ragnaroks.org/project/zhagansharp/ReleaseHistory/" + Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") + "." + Functions.Main.DecodeJson_Ver(strJson_Ver, "rver") + "/ZhaGanSharp.exe";
                            isHaveUpdate = true;
                        })
                    );
                }
                else
                {
                    this.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(delegate
                        {
                            this.TextBlock_RemoteVer.Text += "当前是最新版本: "+Functions.Main.DecodeJson_Ver(strJson_Ver, "ver") + "." + Functions.Main.DecodeJson_Ver(strJson_Ver, "rver");
                            this.TextBlock_RemoteVer_Tooltip.Content = "本地版本: " + strVer + "." + strRver;
                        })
                    );
                }
            }
        }
        #endregion

        #region 托盘
        Boolean isShowednIcon = false;
        private void ShowIcon(){
            this.nIcon = new System.Windows.Forms.NotifyIcon();
            this.nIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
            this.nIcon.MouseClick += OnShowIcon;
            this.nIcon.Visible = true;
            if (isShowednIcon == false)
            {
                this.nIcon.ShowBalloonTip(3000, Properties.Resources.AppName + "  " + strVer+"."+strRver, "测试版本,遇到BUG请反馈", System.Windows.Forms.ToolTipIcon.Info);
                isShowednIcon = true;
            }
        }
        private void OnShowIcon(object sender, EventArgs e){
            this.Show();
            this.nIcon.Visible = false;
            this.nIcon.MouseClick -= OnShowIcon;
        }
        #endregion

        #region 关闭程序按钮
        Boolean is_Canvas_CloseApp_Pressed = false;
        private void Canvas_CloseApp_MouseEnter(object sender, MouseEventArgs e)
        {
        }

        private void Canvas_CloseApp_MouseLeave(object sender, MouseEventArgs e)
        {
            is_Canvas_CloseApp_Pressed = false;
        }

        private void Canvas_CloseApp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            is_Canvas_CloseApp_Pressed = true;
        }

        private void Canvas_CloseApp_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (is_Canvas_CloseApp_Pressed) {
                System.Windows.Media.Effects.BlurEffect BlurEffect = new System.Windows.Media.Effects.BlurEffect();
                BlurEffect.Radius = 5;
                BlurEffect.KernelType = System.Windows.Media.Effects.KernelType.Gaussian;
                this.Effect = BlurEffect;
                if (MessageBoxResult.Yes == MessageBox.Show("确认退出" + Properties.Resources.AppName + "吗?", Properties.Resources.AppName, MessageBoxButton.YesNo, MessageBoxImage.Warning))
                {
                    is_Canvas_CloseApp_Pressed = false;
                    this.Close();
                }
                else {
                    is_Canvas_CloseApp_Pressed = false;
                    this.Effect = null;
                }
            }
        }
        #endregion

        #region 最小化按钮
        private void Canvas_AppMinize_MouseEnter(object sender, MouseEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppMinize.Background = (Brush)brushConverter.ConvertFromString("#FF505050");
            brushConverter = null;
        }

        private void Canvas_AppMinize_MouseLeave(object sender, MouseEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppMinize.Background = (Brush)brushConverter.ConvertFromString("#FF2D2D30");
            brushConverter = null;
        }

        private void Canvas_AppMinize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppMinize.Background = (Brush)brushConverter.ConvertFromString("#FF808080");
            brushConverter = null;
        }

        private void Canvas_AppMinize_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.Canvas_AppMinize.IsMouseOver) {
                this.Hide();
                ShowIcon();
            }
        }
        #endregion

        #region 标题栏
        private void Canvas_TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        #endregion

        #region 帮助按钮
        private void Canvas_AppHelp_MouseEnter(object sender, MouseEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppHelp.Background = (Brush)brushConverter.ConvertFromString("#FF505050");
            brushConverter = null;
        }

        private void Canvas_AppHelp_MouseLeave(object sender, MouseEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppHelp.Background = (Brush)brushConverter.ConvertFromString("#FF2D2D30");
            brushConverter = null;
        }

        private void Canvas_AppHelp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_AppHelp.Background = (Brush)brushConverter.ConvertFromString("#FF808080");
            brushConverter = null;
        }

        private void Canvas_AppHelp_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.Canvas_AppHelp.IsMouseOver)
            {
                Windows.HowToUse Window_HowToUse = new Windows.HowToUse();
                Window_HowToUse.Owner = this;
                Window_HowToUse.Show();
            }
        }
        #endregion

        #region 添加网盘列表
        public static String[] CloudDriveList = { "360云盘", "百度网盘" };
        //public static String[] CloudDriveListURL = { };
        private void ComboBox_CloudDrive_Init()
        {
            /*for (Int32 i = 0; i <= CloudDriveList.Length-1; i++){this.ComboBox_CloudDrive.Items.Add(CloudDriveList[i]);}
            this.ComboBox_CloudDrive.SelectedIndex=0;*/
            //this.ComboBox_CloudDrive.ItemsSource = CloudDriveList;
            this.ComboBox_CloudDrive.DataContext = CloudDriveList;
        }
        #endregion

        #region 开始榨干 按钮
        Boolean continueZhaGan = true;
        private void Canvas_GetitButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BrushConverter brushConverter = new BrushConverter();
            this.Canvas_GetitButton.Background = (Brush)brushConverter.ConvertFromString("#FF808080");
            brushConverter = null;
        }

        private void Canvas_GetitButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.Canvas_GetitButton.IsMouseOver && continueZhaGan)
            {
                BrushConverter brushConverter = new BrushConverter();
                this.Canvas_GetitButton.Background = (Brush)brushConverter.ConvertFromString("#FF505050");
                brushConverter = null;
                ZhaGan();
            }
            else if (this.Canvas_GetitButton.IsMouseOver && continueZhaGan == false)
            {
                ZhaGanThread.Abort();
                AbleUIE();
                this.TextBlock_GetitText.Text = "开始榨干";
                continueZhaGan = true;
            }
        }
        #endregion

        #region UIE禁用或启用
        private void DisableUIE()
        {
            this.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate {
                    this.ComboBox_CloudDrive.IsEnabled = false;
                    this.Canvas_GetitButton.IsEnabled = false;
                    this.TextBox_InputURL.IsEnabled = false;
                    this.TextBox_GetFileCode.IsEnabled = false;
                })
            );
        }

        private void AbleUIE()
        {
            this.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate{
                    this.ComboBox_CloudDrive.IsEnabled = true;
                    this.Canvas_GetitButton.IsEnabled = true;
                    this.TextBox_InputURL.IsEnabled = true;
                    this.TextBox_GetFileCode.IsEnabled = true;
                })
            );
        }
        #endregion

        #region 榨干线程
        System.Threading.Thread ZhaGanThread,ZhaGanTimer;
        Int32 CloudDriveSelectedIndex;
        String InputURL, GetFileCode;
        Byte[] byteJson; String strJson;
        //System.Windows.Threading.DispatcherTimer ZhaGanTimer;
        private void ZhaGan() {
            if (this.TextBox_InputURL.Text.IndexOf("http://") > -1)
            {
                if (this.TextBox_InputURL.Text.IndexOf("pan.baidu.com") > -1 && this.ComboBox_CloudDrive.SelectedIndex != 1)
                {//百度网盘
                    MessageBox.Show("网盘链接与网盘类型不符", Properties.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else if (this.TextBox_InputURL.Text.IndexOf("yunpan.cn") > -1 && this.ComboBox_CloudDrive.SelectedIndex != 0)
                {//360云盘
                    MessageBox.Show("网盘链接与网盘类型不符", Properties.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    this.TextBlock_GetitText.Text = "榨干中...";
                    this.TextBlock_FileName.Text = "";
                    this.TextBlock_FileSize.Text = "";
                    this.TextBlock_FileType.Text = "";
                    this.TextBlock_UserIP.Text = "";
                    is_GetedTheRes = false;
                    ResType = 0;
                    ZhaGanThread = new System.Threading.Thread(ZhaGanThread_DoWork);
                    ZhaGanThread.IsBackground = true;
                    ZhaGanThread.Name = "ChildThread_ZhaGanDoWork";
                    ZhaGanTimer = new System.Threading.Thread(ZhaGanTimer_DoWork);
                    ZhaGanTimer.IsBackground = true;
                    ZhaGanTimer.Name = "ChildThread_ZhaGanTimerDoWork";
                    DisableUIE();
                    ZhaGanThread.Start(); //Console.WriteLine(ZhaGanThread.Name+"已启动");
                    ZhaGanTimer.Start(); //Console.WriteLine(ZhaGanTimer.Name + "已启动");
                }
            }
            else { MessageBox.Show("不要忘了 http://", Properties.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Warning); }
        }
        private void ZhaGanThread_DoWork() {
            this.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate {
                    this.TextBox_OutputURL.Text = "正在榨干...";
                    CloudDriveSelectedIndex = this.ComboBox_CloudDrive.SelectedIndex;
                    if (this.TextBox_InputURL.Text.IndexOf("|") > -1)
                    {
                        String Temp = this.TextBox_InputURL.Text;
                        this.TextBox_InputURL.Text = Temp.Substring(0, Temp.IndexOf("|"));
                        InputURL = this.TextBox_InputURL.Text;
                        this.TextBox_GetFileCode.Text = Temp.Substring(Temp.IndexOf("|")+1);
                        GetFileCode = this.TextBox_GetFileCode.Text;
                    }
                    else {
                        InputURL = this.TextBox_InputURL.Text;
                        GetFileCode = this.TextBox_GetFileCode.Text;
                    }
                })
            );
            if (GetFileCode == "")
            {
                byteJson = Functions.HttpRequestUtil.Get("http://api.ragnaroks.org/api/zhagansharp/get.php?targettype=" + CloudDriveSelectedIndex + "&targeturl=" + InputURL);
            }
            else {
                byteJson = Functions.HttpRequestUtil.Get("http://api.ragnaroks.org/api/zhagansharp/get.php?targettype=" + CloudDriveSelectedIndex + "&targeturl=" + InputURL + "|" + GetFileCode);
            }
            //Console.WriteLine("http://api.ragnaroks.org/api/zhagansharp/get.php?targettype=" + CloudDriveSelectedIndex + "&targeturl=" + InputURL + "|" + GetFileCode);
            strJson = System.Text.Encoding.UTF8.GetString(byteJson, 0, byteJson.Length);
            if (Functions.Main.DecodeJson(strJson, "Status") == "200" && Functions.Main.DecodeJson(strJson, "Result") != null)
            {
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate
                    {
                        this.TextBox_OutputURL.Text = Functions.Main.DecodeJson(strJson, "Result");
                        this.TextBlock_GetitText.Text = "开始榨干";
                        this.TextBlock_FileName.Text = Functions.Main.DecodeJson(strJson, "SourceName");
                        this.TextBlock_FileSize.Text = Functions.Main.DecodeJson(strJson, "SourceSize");
                        this.TextBlock_FileType.Text = Functions.Main.DecodeJson(strJson, "SourceType");
                        for (int i=0; i <= ResTypeListLength-1; i++)
                        {// 匹配文件类型
                            if (ResTypeList[i].IndexOf(Functions.Main.DecodeJson(strJson, "SourceType")) > -1) { ResType = i; Console.WriteLine("文件类型: "+i); }
                        }
                        this.TextBlock_UserIP.Text = Functions.Main.DecodeJson(strJson, "UserIP");
                        is_GetedTheRes = true;
                        Properties.Settings.Default.GetedTimes = Properties.Settings.Default.GetedTimes + 1;
                        Properties.Settings.Default.Save();
                        this.TextBlock_GetedTimes.Text = "已榨干次数: "+Properties.Settings.Default.GetedTimes.ToString();
                        tt = new Windows.TopmostTooltip(); tt.Owner = this;
                        tt.TextBlock_Title.Text = Properties.Resources.TopmostTooltip_Title_Success;
                        tt.TextBlock_Content.Text ="\""+ this.TextBlock_FileName.Text+"\""+Properties.Resources.TopmostTooltip_Content_Success;
                        tt.TextBlock_OtherInfo.Text = "IP: " + Functions.Main.DecodeJson(strJson, "UserIP") + "  剩余次数: " + Functions.Main.DecodeJson(strJson, "Rest");
                        tt.Show();
                    })
                );
                ZhaGanTimer.Abort();
                AbleUIE();
                byteJson=null;
                strJson = null;
            }
            else { 
                ZhaGanTimer.Abort();
                AbleUIE();
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate
                    {
                        this.TextBlock_GetitText.Text = "开始榨干";
                        this.TextBox_OutputURL.Text = "榨干失败,错误代码:" + Functions.Main.DecodeJson(strJson, "Status");
                        this.TextBlock_UserIP.Text = Functions.Main.DecodeJson(strJson, "UserIP");
                    })
                );
                byteJson=null;
                strJson = null;
            }
        }

        /// <summary>
        /// 榨干耗时计时,超过10秒提示手动停止任务
        /// </summary>
        private void ZhaGanTimer_DoWork(){
            for (Int32 time = 1; time <= 10; time++){
                System.Threading.Thread.Sleep(1000);
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate { this.TextBlock_GetitText.Text="耗时"+time.ToString()+"秒"; })
                );
            }
            if(MessageBox.Show("已耗时10秒,是否继续等待?",Properties.Resources.AppName,MessageBoxButton.YesNo,MessageBoxImage.Question)==MessageBoxResult.Yes){
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate { this.TextBlock_GetitText.Text = "停止榨干"; this.Canvas_GetitButton.IsEnabled = true; this.TextBox_OutputURL.Text = "任务已超时,但继续等待响应中..."; })
                );
                continueZhaGan = false;
                //ZhaGanTimer.Abort(); ZhaGanTimer.Join(); 
                Console.WriteLine(ZhaGanTimer.Name+"已退出");
            }else{
                ZhaGanThread.Abort(); ZhaGanThread.Join(); Console.WriteLine(ZhaGanThread.Name+"已退出");
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate { this.TextBlock_GetitText.Text = "已终止任务"; this.TextBox_OutputURL.Text = "任务超时,已终止榨干."; })
                );
                System.Threading.Thread.Sleep(1000);
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(delegate { this.TextBlock_GetitText.Text = "开始榨干"; AbleUIE(); })
                );
                //ZhaGanTimer.Abort(); ZhaGanTimer.Join();
                Console.WriteLine(ZhaGanTimer.Name + "已退出");
            }
        }
        #endregion

        #region 根据输入的URL识别网盘类型
        private void TextBox_InputURL_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            this.TextBox_InputURL.Text = this.TextBox_InputURL.Text.Replace(" ", "");
            if (this.TextBox_InputURL.Text.IndexOf("yunpan.cn") > -1)
            {// 判断360云盘
                this.ComboBox_CloudDrive.SelectedIndex = 0;
                this.TextBox_GetFileCode.Text = "";
                if (this.TextBox_InputURL.Text.IndexOf("（提取码：") > -1) {
                    this.TextBox_InputURL.Text=this.TextBox_InputURL.Text.Replace("（提取码：", "|");
                    this.TextBox_InputURL.Text = this.TextBox_InputURL.Text.Replace("）", "");
                }
            }
            else if (this.TextBox_InputURL.Text.IndexOf("pan.baidu.com") > -1)
            {// 判断百度网盘
                this.ComboBox_CloudDrive.SelectedIndex = 1;
                this.TextBox_GetFileCode.Text = "";
                if (this.TextBox_InputURL.Text.IndexOf("链接:") > -1 || this.TextBox_InputURL.Text.IndexOf("密码:") > -1)
                {
                    this.TextBox_InputURL.Text = this.TextBox_InputURL.Text.Replace("链接:", "");
                    this.TextBox_InputURL.Text = this.TextBox_InputURL.Text.Replace("密码:", "|");
                }
            }
            else { this.TextBox_GetFileCode.Text = ""; }
        }
        #endregion

        #region 下载资源按钮
        private void Canvas_FileDownloadButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void Canvas_FileDownloadButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void Canvas_FileDownloadButton_MouseEnter(object sender, MouseEventArgs e)
        {

        }

        private void Canvas_FileDownloadButton_MouseLeave(object sender, MouseEventArgs e)
        {

        }
        #endregion

        #region 预览资源按钮
        Boolean is_GetedTheRes = false;
        // 0.其他文件 1.MP3音频文件 2.MP4视频文件
        static String[] ResTypeList ={"unknown","audio/mpeg","video/mpeg","video/mp4" };
        Int32 ResType = 0; Int32 ResTypeListLength = ResTypeList.GetLength(0);
        private void Canvas_FilePreviewButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (this.Canvas_FilePreviewButton.IsMouseOver) {
                if (is_GetedTheRes) 
                {
                    switch (ResType) {
                        case 0:
                            MessageBox.Show("该资源文件类型为:\""+ResTypeList[ResType]+"\",无法预览",Properties.Resources.AppName,MessageBoxButton.OK,MessageBoxImage.Information);
                            break;
                        case 1:
                            Windows.MusicPlayer Window_MusicPlayer = new Windows.MusicPlayer();
                            Window_MusicPlayer.Owner = this;
                            Window_MusicPlayer.MediaElement_MusicPlayer.Source = new Uri(this.TextBox_OutputURL.Text);
                            Window_MusicPlayer.TextBlock_Title_Tooltip.Content = "正在预览: " + this.TextBlock_FileName.Text;
                            Window_MusicPlayer.Show();
                            break;
                        case 2:
                        case 3:
                            Windows.VideoPlayer Window_VideoPlayer = new Windows.VideoPlayer();
                            Window_VideoPlayer.Owner = this;
                            Window_VideoPlayer.MediaElement_VideoPlayer.Source = new Uri(this.TextBox_OutputURL.Text);
                            Window_VideoPlayer.TextBlock_Title_Tooltip.Content = "正在预览: " + this.TextBlock_FileName.Text;
                            Window_VideoPlayer.Show();
                            break;
                        default:
                            MessageBox.Show("该资源文件类型为:\"" + ResTypeList[ResType] + "\",无法预览", Properties.Resources.AppName, MessageBoxButton.OK, MessageBoxImage.Information);
                            break;
                    }
                }
                else {
                    MessageBox.Show("还未进行过解析",Properties.Resources.AppName,MessageBoxButton.OK,MessageBoxImage.Warning);
                }
            }
        }
        #endregion

        #region 弹出更新
        String UpdateDownloadURI;
        Boolean isHaveUpdate = false;
        private void TextBlock_RemoteVer_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (isHaveUpdate && this.TextBlock_RemoteVer.IsMouseOver)
            {
                System.Diagnostics.Process.Start(UpdateDownloadURI);
            }
        }
        #endregion
    }
}
